﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Artemis.Core;
using System.Data.Common;
using System.Data;
using System.Text.RegularExpressions;

namespace Artemis.Data.ProxyProvider
{
    public class ProxyCommand : DbCommandWrapper
    {
        private ProxyConnection _con;
        private ProxyCommandDefinition _define;
        public ProxyCommand(DbCommand wrappedCommand, DbCommandDefinitionWrapper commandDefinition)
            : base(wrappedCommand, commandDefinition)
        {
            _con = base.DbConnection as ProxyConnection;
            _define = commandDefinition as ProxyCommandDefinition;
        }

        protected override DbConnection DbConnection {
            get {
                return base.DbConnection;
            }
            set {
                base.DbConnection = value;
                _con = base.DbConnection as ProxyConnection;
            }
        }

        public override string CommandText {
            get {
                return base.CommandText;
            }
            set {
                base.CommandText = value;
                _define.IsReadOnly = IsQuery(CommandText);
            }
        }

        static readonly Regex _reg = new Regex(@"^\W*[(update)|(delete)\(insert)]+");
        private bool IsQuery(string cmdText) {
            return !_reg.Match(cmdText).Success;
        }
        /// <summary>
        /// Executes a SQL statement against a connection object.
        /// </summary>
        /// <returns>The number of rows affected.</returns>
        public override int ExecuteNonQuery()
        {
            _con.OpenConnection(this.Definition as ProxyCommandDefinition);
            return WrappedCommand.ExecuteNonQuery();
        }

        /// <summary>
        /// Executes the query and returns the first column of the first row in the result set returned by the query. All other columns and rows are ignored.
        /// </summary>
        /// <returns>
        /// The first column of the first row in the result set.
        /// </returns>
        public override object ExecuteScalar()
        {
            _con.OpenConnection(this.Definition as ProxyCommandDefinition);
            return WrappedCommand.ExecuteScalar();
        }

        /// <summary>
        /// Executes the command text against the connection.
        /// </summary>
        /// <param name="behavior">An instance of <see cref="T:System.Data.CommandBehavior"/>.</param>
        /// <returns>
        /// A <see cref="T:System.Data.Common.DbDataReader"/>.
        /// </returns>
        protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
        {
            _con.OpenConnection(this.Definition as ProxyCommandDefinition);
            return WrappedCommand.ExecuteReader(behavior);
        }
    }
}
